// 统计单词词频 输出前十的单词
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
typedef struct words
{
	char *word;
	int num;
	struct words *next;
};

// 把单词插入链表
void insert(words *list, char word[])
{
	words *p = list;
	int flag = 0;
	while (p->next)
	{
		if (strcmp(p->next->word, word) == 0)
		{
			p->next->num++;
			// 往前进行调整
			words *t = list;
			while (t->next && t->next->num > p->next->num)
			{
				t = t->next;
			}
			words *q = p->next;
			p->next = q->next;
			q->next = t->next;
			t->next = q;
			flag = 1;
			break;
		}
		p = p->next;
	}
	// 没有找到 插入一个新的节点
	if (!flag)
	{
		list->num++;
		words *newword = (words *)malloc(sizeof(words));
		newword->word = (char *)malloc(sizeof(char) * strlen(word));
		strcpy(newword->word, word);
		newword->num = 1;
		newword->next = p->next;
		p->next = newword;
	}
}

void extract()
{
	words *list = (words *)malloc(sizeof(words));
	list->num = 0;
	list->next = NULL;
	// 打开文件
	FILE *fp;
	if ((fp = fopen("words.txt", "r")) == NULL)
	{
		exit(EXIT_FAILURE);
	}
	// 提取单词
	char word[20];
	// 读取单词的最好方法
	while (fscanf(fp, "%19s", word) == 1)
	{
		int i = 0;
		while (word[i])
		{
			if (isalpha(word[i]))
				word[i] = tolower(word[i]);
			else
			{
				word[i] = '\0';
				break;
			}
			i++;
		}
		// 插入链表
		if (strlen(word))
		{
			printf("%s\n", word);
			insert(list, word);
		}
	}

	// 输出list
	printf("\n\n****************************\n");
	printf("total words:%d\ntop10 is:\n", list->num);
	printf("****************************\n");
	words *p = list->next;
	for (int i = 0; i < 10 && p; i++)
	{
		printf("%-10s --- %d\n", p->word, p->num);
		p = p->next;
	}
}

int main()
{
	/*******************code*******************/
	extract();
	/******************************************/
	printf("\n\n****************************\n");
	printf("Press Enter key to continue\n");
	getchar();
	return 0;
	/******************************************/
}
